#include "utility.h"
#include "Parse.h"
#include "windows.h"


BOOL_EX my_atoi( char* p_str, int *p_num )
{
	int i_len;
	int i;
	BOOL_EX is_negative = FALSE;
	int i_start_index = 0;
	*p_num = 0;
	i_len = strlen(p_str);
	if(i_len == 0 || i_len > 10)
	{
		return FALSE;
	}
	if (p_str[0] == '-')
	{
		is_negative = TRUE;
		i_start_index = 1;
	}
	for (i = i_start_index; i < i_len; ++ i)
	{
		if(!is_number(p_str[i]))
		{
			if (p_str[i] == '.')
			{
				return TRUE;
			}
			return FALSE;
		}
		(*p_num) = (*p_num) * 10 + p_str[i] - '0';
	}
	if (is_negative == TRUE)
	{
		(*p_num) = -(*p_num);
	}
	return TRUE;
}


BOOL_EX my_atof( char* p_str, float *p_num )
{
	int i_len;
	int i;
	int i_dot_amount = 0;
	char* p_buf;
	int i_index = 0;
	BOOL_EX b_ret;
	int int_value;
	int fraction_bit = 0;
	int i_pow = 1;
	BOOL_EX is_negative = FALSE;
	int i_start_index = 0;
	i_len = strlen(p_str);
	if (p_str[0] == '-')
	{
		is_negative = TRUE;
		i_start_index = 1;
	}
	p_buf = (char*)malloc(i_len + 1);
	for (i = i_start_index; i < i_len; ++ i)
	{
		if(! is_number(p_str[i]))
		{
			if(p_str[i] == '.')
			{
				if(i_dot_amount <= 0)
				{
					i_dot_amount = 1;
					continue;
				}
				else
				{
					return FALSE;
				}
			}
			else
			{
				return FALSE;
			}
		}
		else
		{
			// if the dot has been encountered
			if(i_dot_amount == 1)
			{
				++ fraction_bit;
			}
		}
		if(i_index == i_len)
		{
			return FALSE;
		}
		p_buf[i_index ++] = p_str[i];
	}
	p_buf[i_index] = 0;
	b_ret = my_atoi(p_buf, &int_value);
	if(b_ret == FALSE)
	{
		return FALSE;
	}
	for (i = 0; i < fraction_bit; ++ i)
	{
		i_pow *= 10;
	}
	*p_num = (float)((double)int_value / (double)i_pow);
	if (is_negative == TRUE)
	{
		*p_num = - *p_num;
	}
	free(p_buf);
	p_buf = NULL;
	return TRUE;
}


void append_string_to_string( char** pp_appendee, char* p_appender,int *p_cur_size)
{
	int i_str_len = strlen(p_appender);
	(*p_cur_size) += (i_str_len + 1);
	// The first time
	if((*p_cur_size) == (i_str_len + 1))
	{
		(*pp_appendee) = (char*)malloc(sizeof(char) * (*p_cur_size));
		memset(*pp_appendee, 0, *p_cur_size);
	}
	else 
	{
		(*pp_appendee) = (char*)realloc((*pp_appendee), sizeof(char) * (*p_cur_size));  
	}
	strcat(*pp_appendee, p_appender);
}




